import { TableToolbar } from "@/components/grid/TableToolbar";
import { Table } from "antd";
import type { ColumnsType, TableProps } from "antd/es/table";
import type React from "react";
import { useMemo, useState } from "react";

interface CustomTableProps<T> extends Omit<TableProps<T>, "columns" | "size" | "rowKey" | "pagination"> {
	columnsConfig: ColumnsType<T>;
	dataSource: T[];
	loading?: boolean;
	total?: number;
	current?: number;
	pageSize?: number;
	selectedRowKeys: React.Key[];
	onPageChange?: (page: number, pageSize: number) => void;
	setSelectedRowKeys: (keys: React.Key[]) => void;
	selectable?: boolean;
	initialSelectedValues?: string[];
	onRefresh: () => void;
	toolbarButtons?: React.ReactNode; // 允许自定义按钮区域
}

function CustomTable<T extends { id: React.Key } = any>({
	columnsConfig,
	dataSource,
	loading = false,
	total,
	current,
	pageSize,
	selectedRowKeys = [],
	setSelectedRowKeys,
	onPageChange,
	selectable = false,
	initialSelectedValues,
	onRefresh,
	toolbarButtons,
	...tableProps
}: CustomTableProps<T>) {
	const [selectedValues, setSelectedValues] = useState<string[]>(
		initialSelectedValues ??
			columnsConfig.filter((col) => col.key !== "operation").map((col) => (col.key ? String(col.key) : "")),
	);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	const filteredColumns = useMemo(
		() =>
			columnsConfig.filter((col) => col.key === "operation" || selectedValues.includes(col.key ? String(col.key) : "")),
		[columnsConfig, selectedValues],
	);

	return (
		<>
			<div className="flex justify-between mb-4">
				<div className="flex gap-2">{toolbarButtons}</div>
				<TableToolbar
					onRefresh={onRefresh}
					onSizeChange={setTableSize}
					columns={columnsConfig}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				{...tableProps}
				rowKey="id"
				columns={filteredColumns}
				dataSource={dataSource}
				size={tableSize}
				rowSelection={
					selectable
						? {
								type: "checkbox",
								selectedRowKeys,
								onChange: setSelectedRowKeys,
							}
						: undefined
				}
				pagination={
					total && pageSize
						? {
								total,
								current,
								pageSize,
								onChange: onPageChange,
							}
						: false
				}
			/>
		</>
	);
}

export default CustomTable;
